#!/bin/bash
set -e

# 等待数据库准备就绪的函数
wait_for_db() {
  echo "Waiting for database to be ready..."
  # 从环境变量中获取数据库连接信息
  DB_HOST=$(echo $MYSQL_ADDRESS | cut -d':' -f1)
  DB_PORT=$(echo $MYSQL_ADDRESS | cut -d':' -f2)
  
  # 尝试连接数据库，最多尝试30次
  for i in {1..30}; do
    nc -z $DB_HOST $DB_PORT && echo "Database is ready!" && return 0
    echo "Database is not ready yet, waiting... ($i/30)"
    sleep 2
  done
  
  echo "Could not connect to database after 30 attempts. Exiting."
  exit 1
}

# 应用数据库迁移
apply_migrations() {
  echo "Applying database migrations..."
  python3 manage.py migrate --noinput
  echo "Migrations applied successfully!"
}

# 收集静态文件
collect_static() {
  echo "Collecting static files..."
  python3 manage.py collectstatic --noinput
  echo "Static files collected successfully!"
}

# 主函数
main() {
  # 等待数据库准备就绪
  wait_for_db
  
  # 应用数据库迁移
  apply_migrations
  
  # 收集静态文件
  collect_static
  
  # 启动Gunicorn服务器
  echo "Starting Gunicorn server..."
  exec gunicorn wxcloudrun.wsgi:application \
    --bind 0.0.0.0:80 \
    --workers 3 \
    --timeout 120 \
    --access-logfile - \
    --error-logfile - \
    --log-level info
}

# 执行主函数
main
